package com.ruoyi.web.controller.shop.goods;

import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.mapper.NormalMapper;
import com.ruoyi.system.service.*;
import com.ruoyi.system.service.req.NormalDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: ruohao
 * @Date: 2023/9/2
 **/
@Api("点餐菜单")
@RestController
@RequestMapping("/shop/normal")
public class NormalController extends BaseController {
    @Resource
    private NormalService normalService;

    @Resource
    private RestaurantGoodsService restaurantGoodsService;

    @Resource
    private ApproveService approveService;

    @Resource
    private RestaurantOrderService restaurantOrderService;

    @Resource
    private RestaurantOrderDetailService restaurantOrderDetailService;

    @Resource
    private NormalMapper normalMapper;

    @Log(title = "点餐菜单导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Normal normal)
    {
        List<Normal> list = normalService.selectList(normal);
        List<NormalDTO> normalDTOS = fillToDTO(list);
        ExcelUtil<NormalDTO> util = new ExcelUtil<NormalDTO>(NormalDTO.class);
        util.exportExcel(response, normalDTOS, "点餐菜单");
    }

    @ApiOperation("pc端分页获取点餐菜单")
    @GetMapping("/pclist")
    public TableDataInfo pclist(Normal normal)
    {
        startPage();
        List<Normal> list = normalMapper.selectListWithGoods(normal);
        return getDataTable(fillToDTO(list));
    }


    @ApiOperation("分页获取点餐菜单")
    @GetMapping("/list")
    public TableDataInfo list(Normal normal)
    {
        startPage();
        List<Normal> list = normalService.selectList(normal);
        return getDataTable(fillToDTO(list));
    }


    @ApiOperation("获取全部点餐菜单")
    @GetMapping("/listAll")
    public TableDataInfo listAll(Normal normal) {
        logger.info("获取全部点餐菜单 {}", JSON.toJSONString(normal));
        List<Normal> list = normalService.selectAll(normal);
        if (CollectionUtils.isEmpty(list)) {
            return getDataTable(new ArrayList<>());
        }
        List<NormalDTO> normalDTOS = fillToDTO(list);
        normalDTOS = normalDTOS.stream()
//                .filter(n -> "通过".equals(n.getApproveStatus()))
                .filter(n -> "启用".equals(n.getStatus()))
                .collect(Collectors.toList());
        if (!"h5".equals(normal.getAppSource())) {
            return getDataTable(normalDTOS);
        }
        List<RestaurantOrder> orders = restaurantOrderService.getNormalOrderList(RestaurantOrder.builder().type("点餐网上订单").status("购物车").customerId(SecurityUtils.getUserId()).build());
        logger.info("获取全部点餐菜单H5 查询购物车 {}", JSON.toJSONString(orders));
        if (CollectionUtils.isEmpty(orders)) {
            return getDataTable(normalDTOS);
        }
        RestaurantOrder cart = orders.get(0);
        List<RestaurantOrderDetail> orderDetails = restaurantOrderDetailService.getNormalOrderDetailList(RestaurantOrderDetail.builder().orderId(cart.getId()).build());
        logger.info("获取全部点餐菜单H5 查询购物车详情 {}", JSON.toJSONString(orders));
        if (CollectionUtils.isEmpty(orderDetails)) {
            return getDataTable(normalDTOS);
        }
        Map<Long, NormalDTO> normalDTOMap = normalDTOS.stream().collect(Collectors.toMap(NormalDTO::getId, n -> n));
        for (RestaurantOrderDetail detail : orderDetails) {
            if (detail.getNormalId() == null) {
                continue;
            }
            NormalDTO normalDTO = normalDTOMap.get(detail.getNormalId());
            if (normalDTO == null) {
                continue;
            }
            normalDTO.setCount(detail.getCount() == null ? 0 : detail.getCount());
        }
        return getDataTable(normalDTOS);
    }

    //("@ss.hasPermi('store:resource:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id)
    {
        return success(fillOneToDTO(normalService.selectById(id)));
    }

    @Log(title = "添加点餐菜单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@Validated @RequestBody Normal normal)
    {
        String area = SecurityUtils.getUserLocation();
        if (StringUtils.isBlank(area) || area.equals("全部")) {
            throw new BaseException("园区为全部的用户无法下单");
        }

        normal.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        Boolean result = normalService.create(normal);
        if (!result) {
            return error();
        }
//        ApproveMission approveMission = new ApproveMission();
//        approveMission.setApplicant(SecurityUtils.getUserId());
//        approveMission.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
//        approveMission.setStatus("审批中");
//        approveMission.setActivityType("点餐菜单审批");
//        approveMission.setActivityId(normal.getId());
//        approveMission.setName("点餐菜单审批");
//        approveService.createApproveMission(approveMission);
        return success();
    }

    @Log(title = "编辑点餐菜单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody Normal normal) {
        normal.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        Boolean result = normalService.update(normal);
        if (!result) {
            return error();
        }
//        ApproveMission approveMission = approveService.getApproveMissionByActivityd(normal.getId(), "点餐菜单审批");
//        if (approveMission == null) {
//            ApproveMission approveMissionCreateDO = new ApproveMission();
//            approveMissionCreateDO.setApplicant(SecurityUtils.getUserId());
//            approveMissionCreateDO.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
//            approveMissionCreateDO.setStatus("审批中");
//            approveMissionCreateDO.setActivityType("点餐菜单审批");
//            approveMissionCreateDO.setActivityId(normal.getId());
//            approveMissionCreateDO.setName("点餐菜单审批");
//            approveService.createApproveMission(approveMissionCreateDO);
//        } else {
//            if ("通过".equals(approveMission.getStatus()) ||
//                "拒绝".equals(approveMission.getStatus())) {
//                ApproveMission approveMissionCreateDO = new ApproveMission();
//                approveMissionCreateDO.setApplicant(SecurityUtils.getUserId());
//                approveMissionCreateDO.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
//                approveMissionCreateDO.setStatus("审批中");
//                approveMissionCreateDO.setActivityType("点餐菜单审批");
//                approveMissionCreateDO.setActivityId(normal.getId());
//                approveMissionCreateDO.setName("点餐菜单审批");
//                approveService.createApproveMission(approveMissionCreateDO);
//            }
//        }
        return success();
    }

    @Log(title = "菜品管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id)
    {
        return toAjax(normalService.deleteById(id));
    }

    private List<NormalDTO> fillToDTO(List<Normal> normals) {
        if (CollectionUtils.isEmpty(normals)) {
            return new ArrayList<>();
        }
        logger.info("===========");
        logger.info("{}", JSON.toJSONString(normals));
        List<Long> goodsIds = normals.stream().map(Normal::getGoodsId).collect(Collectors.toList());
        Map<Long, RestaurantGoods> goodsMap = restaurantGoodsService.selectByIds(goodsIds).stream().collect(Collectors.toMap(RestaurantGoods::getId, g -> g));
        List<NormalDTO> normalDTOS = normals.stream().map(g -> {
            NormalDTO normalDTO = new NormalDTO();
            normalDTO.setId(g.getId());
            normalDTO.setPrice(g.getPrice());
            normalDTO.setGoodsId(g.getGoodsId());
            normalDTO.setStatus(g.getStatus());
            RestaurantGoods restaurantGoods = goodsMap.get(g.getGoodsId());
            if (restaurantGoods != null) {
                normalDTO.setName(restaurantGoods.getName());
                normalDTO.setImage(restaurantGoods.getImage());
                normalDTO.setHot(restaurantGoods.getHot());
                normalDTO.setHun(restaurantGoods.getHun());
                normalDTO.setTaste(restaurantGoods.getTaste());
            }
//            ApproveMission approveMission = approveService.getApproveMissionByActivityd(g.getId(), "点餐菜单审批");
//            if (approveMission == null) {
//                normalDTO.setApproveStatus("未提交审批");
//            } else {
//                normalDTO.setApproveStatus(approveMission.getStatus());
//                normalDTO.setApproveMissionId(approveMission.getId());
//            }
            normalDTO.setCreateBy(g.getCreateBy());
            normalDTO.setCreateTime(g.getCreateTime());
            normalDTO.setUpdateBy(g.getUpdateBy());
            normalDTO.setUpdateTime(g.getUpdateTime());
            normalDTO.setRemark(g.getRemark());
            normalDTO.setCount(0);
            return normalDTO;
        }).collect(Collectors.toList());
        PageInfo<Normal> oldPage = new PageInfo<>(normals);
        Page<NormalDTO> newPage = new Page<>();
        newPage.addAll(normalDTOS);
        newPage.setTotal(oldPage.getTotal());
        return newPage;
    }

    private NormalDTO fillOneToDTO(Normal normal) {
        if (normal == null) {
            return null;
        }
        NormalDTO normalDTO = new NormalDTO();
        normalDTO.setId(normal.getId());
        normalDTO.setPrice(normal.getPrice());
        normalDTO.setGoodsId(normal.getGoodsId());
        normalDTO.setStatus(normal.getStatus());
        RestaurantGoods goods = restaurantGoodsService.selectRestaurantGoodsById(normal.getGoodsId());
        if (goods != null) {
            normalDTO.setName(goods.getName());
            normalDTO.setImage(goods.getImage());
            normalDTO.setHot(goods.getHot());
            normalDTO.setHun(goods.getHun());
            normalDTO.setTaste(goods.getTaste());
        }
        normalDTO.setCreateBy(normal.getCreateBy());
        normalDTO.setCreateTime(normal.getCreateTime());
        normalDTO.setUpdateBy(normal.getUpdateBy());
        normalDTO.setUpdateTime(normal.getUpdateTime());
        normalDTO.setRemark(normal.getRemark());
        return normalDTO;
    }
}
